package com.admin.service.impl;

import com.admin.common.enums.DeclareLogTypeEnum;
import com.admin.common.enums.DeclareScoreStatusEnum;
import com.admin.common.enums.MemberLevelEnum;
import com.admin.common.exception.BizException;
import com.admin.domain.*;
import com.admin.mapper.*;
import com.admin.req.declarereturn.ReturnModuleReq;
import com.admin.req.declarereturn.ReturnReq;
import com.admin.service.DeclareLogService;
import com.admin.service.DeclareReturnService;
import com.admin.service.DeclareScoreService;
import com.admin.service.RegionsService;
import com.admin.vo.ResultVO;
import com.admin.vo.declareDetail.retrunback.ReturnModuleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 申报回退
 * @author yangzhongliang
 * @date 2022/05/16
 */
@Slf4j
@Service
public class DeclareReturnServiceImpl implements DeclareReturnService {
    @Autowired
    private DeclareMapper declareMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private DeclareReturnModuleMapper returnModuleMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private DeclareLogService logService;
    @Autowired
    private RegionsService regionsService;


    @Override
    public ResultVO save(Integer userId, ReturnReq returnReq, String userLevel) {
        //查询当前登录用户所属社区
        AdminDO adminDO = adminMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(adminDO)) {
            throw new BizException(-1, "登录信息已失效,请重新登录!");
        }

        if (null == returnReq.getDeclareId() || returnReq.getDeclareId() <= 0) {
            throw new BizException(-1, "参数declareId无效,请检查!");
        }

        Declare declare = declareMapper.selectByPrimaryKey(returnReq.getDeclareId());
        if (Objects.isNull(declare)) {
            throw new BizException(-1, "申报信息不存在或已删除!");
        }

        String userLevelName = regionsService.getDeclareRegionName(declare, userLevel);

        //回退 - 是否需要修改
        StringBuffer remarkBuffer = new StringBuffer();
        List<DeclareReturnModule> declareReturnModules = new ArrayList<>();
        for (ReturnModuleReq returnModuleReq : returnReq.getModuleList()) {
            DeclareReturnModule returnModule = new DeclareReturnModule();
            returnModule.setDeclareId(declare.getId());
            returnModule.setModuleName(returnModuleReq.getModuleName());
            returnModule.setModuleCode(returnModuleReq.getModuleCode());
            returnModule.setIsReturn(returnModuleReq.getIsReturn());
            returnModule.setRemark(returnModuleReq.getRemark());
            returnModule.setUserLevel(adminDO.getMemberLevel());
            returnModule.setUserLevelName(userLevelName);
            returnModule.setCreateId(adminDO.getUserId());
            returnModule.setCreateName(adminDO.getRealname());
            returnModule.setCreateMobile(adminDO.getMobile());
            declareReturnModules.add(returnModule);
            if (returnModule.getIsReturn() == 1) {
                remarkBuffer.append(returnModule.getModuleName()).append(":").append(returnModule.getRemark()).append(",");
            }
        }
        DeclareLog declareLog = new DeclareLog();
        declareLog.setDeclareId(declare.getId());
        declareLog.setUserLevel(userLevel);
        declareLog.setUserLevelName(userLevelName);
        if (userLevel.equals(MemberLevelEnum.AREA.getKey())) {
            declareLog.setContent("【"+userLevelName+"】回退至【"+declare.getVillageName()+"】");
            declareLog.setOperatorType(DeclareLogTypeEnum.TYPE_20.getKey());
        } else if (userLevel.equals(MemberLevelEnum.CITY.getKey())) {
            declareLog.setContent("【"+userLevelName+"】回退至【"+regionsService.getDeclareRegionName(declare, MemberLevelEnum.AREA.getKey())+"】");
            declareLog.setOperatorType(DeclareLogTypeEnum.TYPE_30.getKey());
        } else if (userLevel.equals(MemberLevelEnum.PROVINCE.getKey())) {
            declareLog.setContent("【"+userLevelName+"】回退至【"+regionsService.getDeclareRegionName(declare, MemberLevelEnum.CITY.getKey())+"】");
            declareLog.setOperatorType(DeclareLogTypeEnum.TYPE_40.getKey());
        }
        declareLog.setRemark(remarkBuffer.toString());
        ((DeclareReturnService) AopContext.currentProxy()).transactionSave(declare, declareReturnModules, declareLog);
        return ResultVO.ok(true);
    }


    /**
     * 申报回退 - 公共方法
     * @param declare
     * @param returnModules
     */
    @Transactional
    @Override
    public void transactionSave(Declare declare, List<DeclareReturnModule> returnModules, DeclareLog declareLog) {
        //插入回退明细
        for (DeclareReturnModule returnModule : returnModules) {
            returnModuleMapper.insertSelective(returnModule);
        }
        //需要判断 - 是否是 区县，市，省 回退
        Declare updateDeclare = new Declare();
        updateDeclare.setId(declare.getId());
        if (declareLog.getUserLevel().equals(MemberLevelEnum.AREA.getKey())) {
            updateDeclare.setScoreStatus(DeclareScoreStatusEnum.AREA_RETURN.getKey());
        } else if (declareLog.getUserLevel().equals(MemberLevelEnum.CITY.getKey())) {
            updateDeclare.setScoreStatus(DeclareScoreStatusEnum.CITY_RETURN.getKey());
        } else if (declareLog.getUserLevel().equals(MemberLevelEnum.PROVINCE.getKey())) {
            updateDeclare.setScoreStatus(DeclareScoreStatusEnum.PROVINCE_RETURN.getKey());
        }
        declareMapper.updateByPrimaryKeySelective(updateDeclare);
        //更新主表，记录日志
        logService.insertLog(declareLog);
    }

    @Override
    public List<ReturnModuleVO> findModuleByDeclareId(Integer declareId, String moduleName, String userLevel) {
        Map<String,Object> params = new HashMap<>();
        params.put("declareId", declareId);
        params.put("moduleName", moduleName);
        if (StringUtils.isEmpty(userLevel)) {
            userLevel = MemberLevelEnum.PROVINCE.getKey();
        }
        List<String> userLevels = new ArrayList<>();
        //根据用户等级返回能看到的回退信息
        if (userLevel.equals(MemberLevelEnum.AREA.getKey())) {
            userLevels.add(MemberLevelEnum.AREA.getKey());
        } else if (userLevel.equals(MemberLevelEnum.CITY.getKey())) {
            userLevels.add(MemberLevelEnum.AREA.getKey());
            userLevels.add(MemberLevelEnum.CITY.getKey());
        } else if (userLevel.equals(MemberLevelEnum.PROVINCE.getKey())) {
            userLevels.add(MemberLevelEnum.AREA.getKey());
            userLevels.add(MemberLevelEnum.CITY.getKey());
            userLevels.add(MemberLevelEnum.PROVINCE.getKey());
        }
        params.put("userLevels", userLevels);
        List<DeclareReturnModule> returnModuleList = returnModuleMapper.selectByMap(params);
        if (CollectionUtils.isEmpty(returnModuleList)) {
            return null;
        }
        List<ReturnModuleVO> listVOList = new ArrayList<>();
        for (DeclareReturnModule module : returnModuleList) {
            ReturnModuleVO listVO = new ReturnModuleVO();
            BeanUtils.copyProperties(module, listVO);
            listVOList.add(listVO);
        }
        return listVOList;
    }
}
